<template>
  <div class="static-file-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">静态文件管理</h1>
          <p class="page-description">管理系统生成的静态文件，查看文件统计和清理操作</p>
        </div>
        <div class="header-actions">
          <el-button @click="refreshStatistics" :loading="loading" icon="Refresh">
            刷新统计
          </el-button>
          <el-button type="danger" @click="showClearDialog" icon="Delete">
            清理文件
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.totalFiles || 0 }}</div>
            <div class="stat-label">静态文件总数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.totalSizeFormatted || '0 B' }}</div>
            <div class="stat-label">文件总大小</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ Object.keys(statistics.fileTypeStats || {}).length }}</div>
            <div class="stat-label">文件类型数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.lastGenerated || '未生成' }}</div>
            <div class="stat-label">最后生成时间</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 文件类型统计 -->
    <el-card class="file-types-card" v-if="statistics.fileTypeStats">
      <template #header>
        <div class="card-header">
          <span class="card-title">文件类型统计</span>
        </div>
      </template>
      
      <div class="file-types-grid">
        <div 
          v-for="(count, type) in statistics.fileTypeStats" 
          :key="type"
          class="file-type-item"
        >
          <div class="file-type-icon">{{ getFileTypeIcon(type) }}</div>
          <div class="file-type-info">
            <div class="file-type-name">{{ type.toUpperCase() || '无扩展名' }}</div>
            <div class="file-type-count">{{ count }} 个文件</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operations-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">文件操作</span>
        </div>
      </template>
      
      <div class="operations-grid">
        <el-button type="primary" @click="viewFiles" icon="View">
          查看文件列表
        </el-button>
        <el-button type="warning" @click="cleanupOldFiles" icon="Delete">
          清理过期文件
        </el-button>
        <el-button type="info" @click="exportStatistics" icon="Download">
          导出统计报告
        </el-button>
        <el-button @click="refreshCache" icon="Refresh">
          刷新缓存
        </el-button>
      </div>
    </el-card>

    <!-- 清理确认对话框 -->
    <el-dialog v-model="clearDialogVisible" title="清理静态文件" width="500px">
      <div class="clear-options">
        <el-alert
          title="警告"
          type="warning"
          description="清理操作将删除选中的静态文件，此操作不可恢复！"
          show-icon
          :closable="false"
        />
        
        <div class="clear-form">
          <el-checkbox-group v-model="clearOptions">
            <el-checkbox label="html">HTML 文件</el-checkbox>
            <el-checkbox label="css">CSS 文件</el-checkbox>
            <el-checkbox label="js">JavaScript 文件</el-checkbox>
            <el-checkbox label="images">图片文件</el-checkbox>
            <el-checkbox label="all">全部文件</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClear" :loading="clearing">
            确认清理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { generateApi } from '@/api/generate'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const clearing = ref(false)
const clearDialogVisible = ref(false)
const clearOptions = ref<string[]>([])

// 用于取消API请求的控制器
let abortController: AbortController | null = null

const statistics = ref({
  totalFiles: 0,
  totalSize: 0,
  totalSizeFormatted: '0 B',
  lastGenerated: '未生成',
  fileTypeStats: {}
})

// 页面加载时获取统计信息
onMounted(() => {
  // 延迟加载，避免影响路由
  setTimeout(() => {
    refreshStatistics()
  }, 100)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  // 取消正在进行的API请求
  if (abortController) {
    abortController.abort()
  }

  // 关闭可能打开的对话框
  clearDialogVisible.value = false

  // 清理loading状态
  loading.value = false
  clearing.value = false
})

// 刷新统计信息
const refreshStatistics = async () => {
  // 如果已经有请求在进行，先取消
  if (abortController) {
    abortController.abort()
  }

  // 创建新的控制器
  abortController = new AbortController()

  loading.value = true
  try {
    // 设置超时时间，避免长时间阻塞
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), 5000)
    })

    // 调用API获取统计信息，添加超时控制
    const apiPromise = generateApi.getStatistics(1)
    const result = await Promise.race([apiPromise, timeoutPromise])

    if (result.code === 0) {
      statistics.value = result.data
      ElMessage.success('统计信息刷新成功')
    } else {
      console.warn('API返回错误:', result.msg)
      // 使用默认数据，不显示错误消息避免干扰用户
      setDefaultStatistics()
    }
  } catch (error) {
    // 如果是主动取消的请求，不处理错误
    if (error.name === 'AbortError') {
      return
    }

    console.error('获取统计信息失败:', error)
    // 静默处理错误，使用默认数据
    setDefaultStatistics()
  } finally {
    loading.value = false
    abortController = null
  }
}

// 设置默认统计数据
const setDefaultStatistics = () => {
  statistics.value = {
    totalFiles: 0,
    totalSize: 0,
    totalSizeFormatted: '0 B',
    lastGenerated: '未生成',
    fileTypeStats: {}
  }
}

// 显示清理对话框
const showClearDialog = () => {
  clearOptions.value = []
  clearDialogVisible.value = true
}

// 确认清理
const confirmClear = async () => {
  if (clearOptions.value.length === 0) {
    ElMessage.warning('请选择要清理的文件类型')
    return
  }

  clearing.value = true
  try {
    // 调用清理API
    await generateApi.clearStaticFiles(clearOptions.value)

    ElMessage.success('文件清理成功')
    clearDialogVisible.value = false

    // 刷新统计信息
    await refreshStatistics()
  } catch (error) {
    console.error('清理文件失败:', error)
    ElMessage.error('清理文件失败')
  } finally {
    clearing.value = false
  }
}

// 查看文件列表
const viewFiles = () => {
  // 跳转到静态文件管理页面
  router.push('/system/static-files')
}

// 清理过期文件
const cleanupOldFiles = async () => {
  try {
    await ElMessageBox.confirm('确定要清理过期文件吗？', '确认操作', {
      type: 'warning'
    })

    // 调用清理过期文件API
    await generateApi.clearStaticFiles(['expired'])

    ElMessage.success('过期文件清理成功')
    await refreshStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理过期文件失败:', error)
      ElMessage.error('清理过期文件失败')
    }
  }
}

// 导出统计报告
const exportStatistics = async () => {
  try {
    // 调用导出API
    const response = await generateApi.exportStatisticsReport(selectedSiteId.value)

    // 创建下载链接
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `静态文件统计报告_${new Date().toISOString().split('T')[0]}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('报告导出成功')
  } catch (error) {
    console.error('导出报告失败:', error)
    ElMessage.error('导出报告失败')
  }
}

// 刷新缓存
const refreshCache = async () => {
  try {
    await ElMessageBox.confirm('确定要刷新缓存吗？', '确认操作', {
      type: 'info'
    })
    
    ElMessage.success('缓存刷新成功')
  } catch {
    // 用户取消操作
  }
}

// 获取文件类型图标
const getFileTypeIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    'html': '📄',
    'css': '🎨',
    'js': '⚡',
    'jpg': '🖼️',
    'jpeg': '🖼️',
    'png': '🖼️',
    'gif': '🖼️',
    'svg': '🎯',
    'pdf': '📕',
    'txt': '📝',
    '': '📁'
  }
  return iconMap[type.toLowerCase()] || '📄'
}
</script>

<style scoped lang="scss">
.static-file-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);

  .page-header {
    margin-bottom: 24px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid #e4e7ed;
    }

    .header-left {
      .page-title {
        font-size: 28px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 8px 0;
        line-height: 1.2;
      }

      .page-description {
        color: #909399;
        margin: 0;
        font-size: 14px;
        line-height: 1.4;
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .statistics-overview {
    margin-bottom: 24px;

    .stat-card {
      background: white;
      padding: 24px;
      border-radius: 12px;
      text-align: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid #e4e7ed;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }

      .stat-number {
        font-size: 32px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 8px;
        line-height: 1;
      }

      .stat-label {
        color: #606266;
        font-size: 14px;
        font-weight: 500;
      }
    }
  }

  .file-types-card,
  .operations-card {
    margin-bottom: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e4e7ed;

    .card-header {
      .card-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .file-types-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;

    .file-type-item {
      display: flex;
      align-items: center;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #e9ecef;

      .file-type-icon {
        font-size: 24px;
        margin-right: 12px;
      }

      .file-type-info {
        .file-type-name {
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
        }

        .file-type-count {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }

  .operations-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;

    .el-button {
      height: 48px;
      font-size: 14px;
    }
  }

  .clear-options {
    .clear-form {
      margin-top: 20px;
      
      .el-checkbox-group {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }
    }
  }
}
</style>
